package Servlet;

import JDBCHelper.MySqlDBUtil;
import JDBCHelper.UsersTableUtil;
import TableObject.Users;
import Util.CookieSave;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;

@WebServlet(name = "Servlet.LoginServlet")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置成与浏览器不同的编码方式，测试过滤器
        //response.setContentType("text/html;charset=GB2312");
        //request.setCharacterEncoding("GB2312");
        //与浏览器相同的编码方式
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        //连接数据库
        Connection connection= MySqlDBUtil.getConnection();
        //Login的处理
        Login(request,response,connection);
        //关闭数据库
        MySqlDBUtil.ShutDown(null,connection);
    }
    void Login(HttpServletRequest request, HttpServletResponse response,Connection connection) throws IOException {
        //获取表单中的数据的值
        Users user=new Users();
        user.setName(request.getParameter("username"));
        user.setPassword(request.getParameter("password"));
        System.out.println("登入用户名："+user.getName());
        System.out.println("登入用户密码："+user.getPassword());
        //验证用户名密码
        UsersTableUtil ur = new UsersTableUtil();
        boolean b = ur.IsUsersExist(connection, user);
        System.out.println("是否存在该用户："+b);
        System.out.println("-------------------------------");
        if(b){
            CookieSave cookieSave=new CookieSave();
            //存储用户名
            cookieSave.Save(response,"username",user.getName(),60*60*24*30);
            //存储密码
            cookieSave.Save(response,"password",user.getPassword(),60*60*24*30);
            HttpSession session =request.getSession(true);
            //成功登录，进入主界面
            response.sendRedirect("yinglang/index.html");
        }else
        {
            response.getWriter().println("登陆失败");
            //登录失败，返回登陆界面
            response.sendRedirect("login.html");
            System.out.println("Login Failed!");
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}